package com.learn.security.modules.security.sms;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.learn.security.modules.security.SecurityConstants;
import com.learn.security.modules.vo.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 短信登录的鉴权过滤器，模仿 UsernamePasswordAuthenticationFilter 实现
 *
 * @author jitwxs
 * @since 2019/1/9 13:52
 */
@Slf4j
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 是否仅 POST 方式
     */
    private boolean postOnly = true;

    public SmsCodeAuthenticationFilter() {
        // 短信登录的请求 post 方式的 /sms/login
        super(new AntPathRequestMatcher(SecurityConstants.SMS_LOGIN_PROCESSING_URL, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        log.info("手机号登录filter");
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        UserDto user = obtainUser(request);
        SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(user);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected UserDto obtainUser(HttpServletRequest request) {
        UserDto user = null;
        try (ServletInputStream is = request.getInputStream()) {
            String bodyStr = IoUtil.read(is, CharsetUtil.CHARSET_UTF_8);
            if (StrUtil.isBlank(bodyStr)) {
                log.info("登录失败,数据错误");
                throw new AuthenticationServiceException("登录失败,数据错误");
            }
            user = JSONUtil.toBean(bodyStr, UserDto.class);
        } catch (IOException e) {
            log.error("读取请求数据失败", e);
            throw new AuthenticationServiceException("登录失败,请求异常");
        }
        if (user == null) {
            log.info("登录失败,数据错误");
            throw new AuthenticationServiceException("登录失败,数据错误");
        }
        if (StrUtil.isBlank(user.getPlateNo())) {
            log.info("登录失败,车牌号为空");
            throw new AuthenticationServiceException("登录失败,车牌号为空");
        }
        if (StrUtil.isBlank(user.getMobile())) {
            log.info("登录失败,手机号为空");
            throw new AuthenticationServiceException("等失败,手机号为空");
        }
        if (StrUtil.isBlank(user.getSmsCode())) {
            log.info("登录失败,验证码为空");
            throw new AuthenticationServiceException("登录失败,验证码为空");
        }
        return user;
    }

    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}
